﻿using System.Collections.Specialized;
using System.Timers;

using NanoMvvm.Collections;

namespace NanoMvvm
{
    public class RotateContentViewModel : PropertyObservableBase
    {
        private readonly Timer tickTimer;
        private int itemIndex;
        private object dataContent;

        private double interval;

        public RotateContentViewModel()
        {
            ContentCollection = new ObservableList<object>();
            ContentCollection.CollectionChanged += OnContentCollectionChanged;
            tickTimer = new Timer();
            tickTimer.Elapsed += OnTick;

            Interval = 2000;

            Setup();
        }

        public ObservableList<object> ContentCollection { get; private set; }

        public double Interval
        {
            get
            {
                return interval;
            }
            set
            {
                SetProperty(ref interval, value, () => Interval);

                Setup();
            }
        }

        public object DataContent
        {
            get
            {
                return dataContent;
            }
            private set
            {
                SetProperty(ref dataContent, value, () => DataContent);
            }
        }

        private void OnTick(object sender, ElapsedEventArgs e)
        {
            itemIndex++;
            itemIndex = itemIndex % ContentCollection.Count;

            DataContent = ContentCollection[itemIndex];
        }

        private void OnContentCollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
        {
            Setup();
        }

        private void Setup()
        {
            DataContent = null;

            if (ContentCollection.Count == 0)
            {
                tickTimer.Stop();
                return;
            }

            itemIndex = 0;

            tickTimer.Stop();
            tickTimer.Interval = Interval;
            tickTimer.AutoReset = true;

            DataContent = ContentCollection[0];

            tickTimer.Start();
        }
    }
}